package com.ingenico.tools.data.chopping;

import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

public class VersatileChopper implements Chopper {
	private static final Logger _logger = Logger.getLogger(VersatileChopper.class.getCanonicalName());

// FIXME : this must be configurable
	protected long maxSamples = 1000000;
	protected int  maxChuncks = 3;

	public void setMaxSamples(long maxSamples) {
		this.maxSamples = maxSamples;
	}

	public void setMaxChuncks(int maxChuncks) {
		this.maxChuncks = maxChuncks;
	}

	public Set<Rectangle2D> getChunkSet (Rectangle2D samplesWindowBounds, int targetLength) {
		final double samplesWindowOffset = samplesWindowBounds.getX();
		final double samplesWindowWidth = samplesWindowBounds.getWidth();

		final double windowPosition = samplesWindowOffset / samplesWindowWidth;

		final int windowID = (int)java.lang.Math.ceil(windowPosition);

		final HashSet<Rectangle2D> chunkSet = new HashSet<Rectangle2D>();

		int actualMaxChuncks = (maxChuncks < 2) ? 2 : maxChuncks;
		long actualMaxSamples = (maxSamples < (2*samplesWindowWidth)) ? (long)(2*samplesWindowWidth) : maxSamples;

		int currentIncrement = 0;
		int currentIndex = windowID;
		long totalSamples = 0;
		int totalSampleChunks = 0;
		while ((totalSampleChunks < actualMaxChuncks) && (totalSamples < actualMaxSamples) ) {
			Rectangle2D currentRectangle = new Rectangle2D.Double ();
			if (currentIndex >= 0) {
				currentRectangle.setRect(
						(currentIndex * samplesWindowWidth),
						samplesWindowBounds.getY(),
						samplesWindowWidth,
						samplesWindowBounds.getHeight()
				);

				chunkSet.add(currentRectangle);
				_logger.fine("Adding Chunck " + currentRectangle);

				totalSamples += samplesWindowWidth;
				++totalSampleChunks;
			}

			currentIncrement = (currentIncrement >= 0) ? -(++currentIncrement) : -(--currentIncrement);
			currentIndex += currentIncrement;
		}
		return chunkSet;
	}

//TODO: remove this main and write a unit test
	public static void main(String[] args) {
		VersatileChopper pipo = new VersatileChopper();
		Rectangle2D rect = new Rectangle2D.Double(3000, 0, 1500, 255);

		pipo.setMaxChuncks(10);
		pipo.setMaxSamples(10000);
		pipo.getChunkSet(rect, 100);
	}

}
